package uml.eventsystem;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Collection;
import java.util.HashMap;

import javax.swing.KeyStroke;

import uml.eventsystem.events.UMLEventId;

public class KeyHandler extends KeyAdapter implements ISubject
{
	private HashMap<KeyStroke, UMLEventId> m_keyMap;
	private static KeyHandler m_keyHandler;
	private SubjectImpl m_subjectImplementation;
	
	/**
	 * private constructor
	 */
	private KeyHandler()
	{
		m_keyMap = KeyMap.getKeyMap();
		m_subjectImplementation = new SubjectImpl(this);
	}
	
	/**
	 * gets m_keyHandler
	 * @return KeyHandler
	 */
//	public static KeyHandler getKeyHandler()
//	{
//		if(m_keyHandler == null)
//			m_keyHandler = new KeyHandler();
//		return m_keyHandler;
//	}
	
	/**
	 * notifies observers when key is pressed.
	 */
	@Override
	public void keyPressed(KeyEvent key)
	{
		KeyStroke keyStroke = KeyStroke.getKeyStroke(key.getKeyCode(), key.getModifiers());
		UMLEventId event = (UMLEventId) m_keyMap.get(keyStroke);
		if(event != null)
			notifyObservers(event);
	}
	
	
	@Override
	public void keyReleased(KeyEvent key)
	{
		
	}
	
	/**
	 * adds observers
	 */
	@Override
	public void addObserver(IObserver observer, UMLEventId eventId) 
	{
		m_subjectImplementation.addObserver(observer, eventId);
	}
	/**
	 * removes observers
	 */
	@Override
	public void removeObserver(IObserver observer, UMLEventId eventId) 
	{
		m_subjectImplementation.removeObserver(observer, eventId);
	}
	
	/**
	 * notifies observers with UMLEventId
	 */
	@Override
	public void notifyObservers(UMLEventId eventId) 
	{
		m_subjectImplementation.notifyObservers(eventId);
	}
	
	/**
	 * registers for all events
	 * @param observer
	 */
	public void registerForAllEvents(IObserver observer) 
	{
		Collection<UMLEventId> events = m_keyMap.values();
		for(UMLEventId event : events)
			addObserver(observer, event);
	}
}
